import { Modal } from "antd";
import { LoadingOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import { subscribe, unsubscribe } from "pubsub-js";
import { useState, useEffect } from "react";
import { connect } from "react-redux";
import { getCheckJoinedGroup, getGroupInfo, getGroupMember, getGroupSet } from "../../assets/js/api";
import { closeGroupInfo, memberRefresh, showGroupInfo } from "../../event-type";

import {
    modal_wrapper,
    group_info_tabs,
    group_info_tabs_item,
    current,
    group_info_content,
    tip_wrapper,
    group_info_main,
} from './index.module.css'
import AvatorUpload from "../avatorUpload";
import GroupInfoLeft from "./groupInfoLeft";
import GroupHoom from "./groupInfoRight/groupHoom";
import GroupMember from "./groupInfoRight/groupMember";
import GroupSet from "./groupInfoRight/groupSet";

function GroupDetail(props) {
    
    const {user} = props;

    const [nowRoom, setNowRoom] = useState();
    const [groupBaseInfo, setGroupBaseInfo] = useState({});     // id, name, avator
    const [groupHoomProps, setGroupHoomProps] = useState({});
    const [groupMemberProps, setGroupMemberProps] = useState({members:[], adminsNum:''});
    const [groupSettingProps, setGroupSettingProps] = useState({});

    const [modalVisibel, setModalVisibel] = useState(false);
    const [loading, setLoading] = useState(true);
    const [loadError, setLoadError] = useState(false);
    const [identity, setIdentity] = useState(-1);    // -1默认值(不显示),0不在群组,1为成员,2为管理,3为群主
    const [tabIndex, setTabIndex] = useState(0);    // 默认为0,非群组人员无法查看其他信息




    useEffect(() => {
		const showGourpInfoToken = subscribe(showGroupInfo, (event, groupData) => {
            setNowRoom(groupData.group_id);
            setGroupBaseInfo(groupData);
            getGroupDetail(groupData.group_id);
            // 注意顺序,因为在后面的数据请求需要用到上面的data,故后显示modal
            setModalVisibel(true);
		});
        const closeGroupInfoToken = subscribe(closeGroupInfo, (event) => {
            closeModal();
        });

		return () => {
			unsubscribe(showGourpInfoToken);
			unsubscribe(closeGroupInfoToken);
		}
    }, []);
    useEffect(() => {
        if (!modalVisibel) {
            setTabIndex(0);
            return;
        }
        // 当前用户对于查看群组的身份
        getCheckJoinedGroup({user_id: user.id,group_id: groupBaseInfo.group_id})
        .then(res => {
            const {code} = res.data;
            if (code !== 0) {
                setIdentity(code - 1);
            }
        })
        .catch(err => {
            console.log(err);
        });
    }, [groupBaseInfo,user,modalVisibel]);
    useEffect(() => {
        setLoadError(false);
        // 当有数据时不再次请求数据
        if (tabIndex === 0) {
            if (!groupHoomProps.group_id) {
                return;
            }
            getGroupDetail(nowRoom);
        } else if (tabIndex === 1) {
            if (groupMemberProps.members.length > 0) {
                return;
            }
            getGroupMemberInfo(nowRoom);
        } else if (tabIndex === 2) {
            if (!!groupSettingProps.group_public) {
                return;
            }
            getGroupSetInfo(nowRoom);
        }
    }, [tabIndex,nowRoom]);
    useEffect(() => {
        const memberRefreshToken = subscribe(memberRefresh, () => {
            getGroupMemberInfo(nowRoom);
        });
        return () => {
			unsubscribe(memberRefreshToken);
        }
    }, [nowRoom])

    function closeModal() {
        // 关闭modal后清除数据
        setModalVisibel(false);

        setGroupHoomProps({});
        setGroupMemberProps({members:[], adminsNum:''});
        setGroupSettingProps({});
        setIdentity(-1);
    }
    function getGroupDetail(group_id) {
        // 获取群组信息
        setLoading(true);

        getGroupInfo({group_id})
        .then(res => {
            const {code, data} = res.data;
            if (code !== 1) {
                // 加载失败
                setLoadError(true);
                return;
            }
            setGroupHoomProps(data);
        })
        .catch(err => {
            console.log(err);
            setLoadError(true);
        })
        .finally(() => {
            setLoading(false);
        });
    }
    function getGroupMemberInfo(group_id) {
        setLoading(true);

        getGroupMember({group_id})
        .then(res => {
            const {code, data, adminsNum} = res.data;
            if (code !== 1) {
                // 加载失败
                setLoadError(true);
                return;
            }
            setGroupMemberProps({members: data, adminsNum});
        })
        .catch(err => {
            console.log(err);
            setLoadError(true);
        })
        .finally(() => {
            setLoading(false);
        });
    }
    function getGroupSetInfo(group_id) {
        // 群组设置显示
        setLoading(true);

        getGroupSet({group_id})
        .then(res => {
            const {code, data} = res.data;
            if (code !== 1) {
                setLoadError(true);
                return;
            }
            setGroupSettingProps({...data,group_id,identity});
        })
        .catch(err => {
            console.log(err);
            setLoadError(true);
        })
        .finally(() => {
            setLoading(false);
        });
    }
    


    return (
        <>
            <Modal
                wrapClassName={modal_wrapper}
                visible={modalVisibel}
                centered={true}
                maskClosable={false}
                footer={null}
                width={800}
                zIndex={1000}
                destroyOnClose
                style={{minWidth: '800px'}}
                bodyStyle={{display: 'flex',paddingTop: '50px'}}
                onCancel={closeModal}
            >
                <GroupInfoLeft
                    group_avator={groupBaseInfo.group_avator}
                    group_name={groupBaseInfo.group_name}
                    group_id={groupBaseInfo.group_id}
                    identity={identity}
                />
                <div className={group_info_content}>
                    <div className={group_info_tabs}>
                        {
                            identity !== 0 ?
                                <>
                                    <div className={`${group_info_tabs_item} ${tabIndex === 0 ? current : ''}`} onClick={() => setTabIndex(0)}>首页</div>
                                    <div className={`${group_info_tabs_item} ${tabIndex === 1 ? current : ''}`} onClick={() => setTabIndex(1)}>成员</div>
                                    <div className={`${group_info_tabs_item} ${tabIndex === 2 ? current : ''}`} onClick={() => setTabIndex(2)}>设置</div>
                                </>:
                                ''
                        }
                    </div> 
                    <div className={group_info_main}>
                        {
                            loadError ?
                                <div className={tip_wrapper} style={{color: '#f00'}}><ExclamationCircleOutlined /></div> :
                                loading ? 
                                    <div className={tip_wrapper}><LoadingOutlined /></div> :
                                        tabIndex === 0 ? <GroupHoom groupInfo={groupHoomProps} identity={identity} /> :
                                        tabIndex === 1 ? <GroupMember {...groupMemberProps} group_id={nowRoom} /> :
                                        tabIndex === 2 ? <GroupSet {...groupSettingProps} /> : 
                                        <div className={tip_wrapper} style={{color: '#f00'}}><ExclamationCircleOutlined /></div>
                        }
                    </div>
                </div>
            </Modal>
            <AvatorUpload />
        </>
    )
}


function mapStateToProps(state) {
    return {
        user: state.user,
    }
}
export default connect(
    mapStateToProps,
    {

    }
)(GroupDetail);

